/*******************************************************************************
 * Copyright 2010 DemandSpot
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.demandspot.client.table;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.ui.Button;

public class SortWidget<RowModel> extends Button {
	
	private static final Labels LABELS = Labels.Util.getLabels();
	
	private DataScrollTable<SortRow> scrollTable;
	private List<CellRenderer<RowModel, ?>> cellRenderers = new ArrayList<CellRenderer<RowModel,?>>();
	private List<Integer> columnsIndexList = new ArrayList<Integer>();
	
	/**
	 * Data table to apply sort on
	 */
	private DataTable<RowModel> dataTable;
	
	public SortWidget(List<CellRenderer<RowModel, ?>> cellRenderers, DataTable<RowModel> dataTable) {
		this.dataTable = dataTable;
		this.cellRenderers = cellRenderers;
		
		setText(LABELS.sortBtnText());
		
		int counter = 0;
		for (Iterator<CellRenderer<RowModel, ?>> iter = cellRenderers.iterator(); iter.hasNext();) {
			CellRenderer<RowModel, ?> cellRenderer = iter.next();
			if (!cellRenderer.isSortable()) {
				iter.remove();
			} else {
				columnsIndexList.add(counter);
			}
			counter++;
		}
	}
	
	protected static class SortRow implements Serializable {
		public static enum Direction {
			Ascending {
				String getLabel() {
					return LABELS.ascending();
				}
			},
			Descending {
				String getLabel() {
					return LABELS.descending();
				}
			};
			
			abstract String getLabel(); 
		};
		private int column = 0;
		private Direction direction = Direction.Ascending;
		
		public SortRow(int column, Direction direction) {
			super();
			this.column = column;
			this.direction = direction;
		}

		protected int getColumn() {
			return column;
		}

		protected Direction getDirection() {
			return direction;
		}
	}
}
